<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      <!-- 欢迎卡片 -->
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <el-card class="welcome-card">
          <div class="welcome-content">
            <div class="welcome-text">
              <h2>欢迎, {{ userInfo.fullName || userInfo.username }}</h2>
              <p>今天是健身的好日子，继续保持吧！</p>
            </div>
            <div class="quick-actions">
              <el-button type="primary" @click="goToAddHealthData">
                <el-icon><Plus /></el-icon>添加健康数据
              </el-button>
              <el-button type="success" @click="goToAddExerciseRecord">
                <el-icon><Plus /></el-icon>记录运动
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 健康数据卡片 -->
      <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
        <el-card class="data-card">
          <template #header>
            <div class="card-header">
              <span>最新健康数据</span>
              <el-button type="text" @click="goToHealthData">查看更多</el-button>
            </div>
          </template>
          <div v-if="latestHealthData">
            <div class="data-item">
              <span class="label">身高：</span>
              <span class="value">{{ latestHealthData.height }} cm</span>
            </div>
            <div class="data-item">
              <span class="label">体重：</span>
              <span class="value">{{ latestHealthData.weight }} kg</span>
            </div>
            <div class="data-item">
              <span class="label">BMI：</span>
              <span class="value" :class="getBmiClass(latestHealthData.bmi)">
                {{ latestHealthData.bmi }} ({{ bmiCategory }})
              </span>
            </div>
            <div class="data-item">
              <span class="label">静息心率：</span>
              <span class="value">{{ latestHealthData.restingHeartRate || '-' }} bpm</span>
            </div>
            <div class="data-item">
              <span class="label">记录时间：</span>
              <span class="value">{{ formatDateTime(latestHealthData.recordDate) }}</span>
            </div>
          </div>
          <div v-else class="no-data">
            <el-empty description="暂无健康数据" :image-size="100">
              <el-button type="primary" @click="goToAddHealthData">添加数据</el-button>
            </el-empty>
          </div>
        </el-card>
      </el-col>
      
      <!-- 运动统计卡片 -->
      <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
        <el-card class="data-card">
          <template #header>
            <div class="card-header">
              <span>运动统计</span>
              <el-button type="text" @click="goToExerciseRecords">查看详情</el-button>
            </div>
          </template>
          <div v-if="exerciseStats.totalDuration">
            <div class="data-item">
              <span class="label">总运动时长：</span>
              <span class="value">{{ formatDuration(exerciseStats.totalDuration) }}</span>
            </div>
            <div class="data-item">
              <span class="label">总消耗卡路里：</span>
              <span class="value">{{ Math.round(exerciseStats.totalCalories) }} kcal</span>
            </div>
            <div class="data-item">
              <span class="label">本周运动次数：</span>
              <span class="value">{{ weeklyExerciseCount }} 次</span>
            </div>
            <div class="recent-exercises">
              <div class="label">近期运动类型：</div>
              <el-tag 
                v-for="(count, type, index) in exerciseStats.typeDistribution" 
                :key="type"
                class="exercise-tag"
                :type="getTagType(index)"
              >
                {{ type }}
              </el-tag>
            </div>
          </div>
          <div v-else class="no-data">
            <el-empty description="暂无运动记录" :image-size="100">
              <el-button type="primary" @click="goToAddExerciseRecord">添加记录</el-button>
            </el-empty>
          </div>
        </el-card>
      </el-col>
      
      <!-- 目标进度卡片 -->
      <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
        <el-card class="data-card">
          <template #header>
            <div class="card-header">
              <span>目标进度</span>
              <el-button type="text" @click="goToFitnessGoals">查看所有</el-button>
            </div>
          </template>
          <div v-if="activeGoals.length > 0">
            <div v-for="goal in activeGoals.slice(0, 3)" :key="goal.id" class="goal-item">
              <div class="goal-title">{{ goal.title }}</div>
              <el-progress 
                :percentage="goal.progress" 
                :status="getProgressStatus(goal.progress)"
                :stroke-width="12"
              />
              <div class="goal-detail">
                <span>目标日期: {{ formatDate(goal.targetDate) }}</span>
              </div>
            </div>
            <div v-if="activeGoals.length > 3" class="more-goals">
              还有 {{ activeGoals.length - 3 }} 个目标
            </div>
          </div>
          <div v-else class="no-data">
            <el-empty description="暂无活跃目标" :image-size="100">
              <el-button type="primary" @click="goToAddFitnessGoal">设定目标</el-button>
            </el-empty>
          </div>
        </el-card>
      </el-col>
      
      <!-- 提醒卡片 -->
      <el-col :xs="24" :sm="12" :md="24" :lg="24" :xl="6">
        <el-card class="data-card">
          <template #header>
            <div class="card-header">
              <span>健康提醒</span>
            </div>
          </template>
          <div class="reminders">
            <div v-if="healthReminders.length > 0">
              <div v-for="(reminder, index) in healthReminders" :key="index" class="reminder-item">
                <el-icon :class="reminder.iconClass"><component :is="reminder.icon" /></el-icon>
                <span>{{ reminder.message }}</span>
              </div>
            </div>
            <el-empty v-else description="暂无健康提醒" :image-size="100" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { getLatestHealthData } from '@/api/healthData'
import { getExerciseStats, getExerciseRecordsByDateRange } from '@/api/exerciseRecord'
import { getFitnessGoalsByStatus } from '@/api/fitnessGoal'
import { getCurrentUser } from '@/api/auth'

const router = useRouter()
const userInfo = ref({})
const latestHealthData = ref(null)
const bmiCategory = ref('')
const exerciseStats = reactive({
  totalDuration: 0,
  totalCalories: 0,
  typeDistribution: {}
})
const activeGoals = ref([])
const weeklyExerciseCount = ref(0)
const healthReminders = ref([])

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const data = await getCurrentUser()
    userInfo.value = data
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 获取最新健康数据
const fetchLatestHealthData = async () => {
  try {
    const response = await getLatestHealthData()
    if (response && response.healthData) {
      latestHealthData.value = response.healthData
      bmiCategory.value = response.bmiCategory || ''
    }
  } catch (error) {
    console.error('获取最新健康数据失败:', error)
    latestHealthData.value = null
    bmiCategory.value = ''
  }
}

// 获取运动统计数据
const fetchExerciseStats = async () => {
  try {
    // 添加默认统计数据，防止后端未返回数据导致前端错误
    let stats = {
      totalDuration: 0,
      totalCalories: 0,
      typeDistribution: {}
    }
    
    try {
      const response = await getExerciseStats()
      if (response) {
        stats = response
      }
    } catch (statsError) {
      console.error('获取运动统计详情失败:', statsError)
      // 继续使用默认值
    }
    
    exerciseStats.totalDuration = stats.totalDuration || 0
    exerciseStats.totalCalories = stats.totalCalories || 0
    exerciseStats.typeDistribution = stats.typeDistribution || {}
    
    // 获取本周运动次数
    try {
      const now = new Date()
      const startOfWeek = new Date(now)
      startOfWeek.setDate(now.getDate() - now.getDay())
      startOfWeek.setHours(0, 0, 0, 0)
      
      console.log('Dashboard - 获取本周运动记录:', {
        开始日期: startOfWeek.toISOString(),
        结束日期: now.toISOString()
      });
      
      // 确保使用ISO日期格式
      const response = await getExerciseRecordsByDateRange(
        startOfWeek.toISOString(),
        now.toISOString()
      )
      
      // 安全地检查响应数据
      if (response && Array.isArray(response)) {
        weeklyExerciseCount.value = response.length;
        console.log('Dashboard - 本周运动记录数量:', weeklyExerciseCount.value);
      } else {
        console.warn('Dashboard - 获取的本周运动记录格式不正确:', response);
        weeklyExerciseCount.value = 0;
      }
    } catch (recordsError) {
      console.error('获取周运动记录失败:', recordsError)
      console.log('错误详情:', recordsError.response?.data)
      weeklyExerciseCount.value = 0
    }
  } catch (error) {
    console.error('获取运动统计失败:', error)
    // 确保即使整个函数失败，也不会影响UI显示
    exerciseStats.totalDuration = 0
    exerciseStats.totalCalories = 0
    exerciseStats.typeDistribution = {}
    weeklyExerciseCount.value = 0
  }
}

// 获取活跃目标
const fetchActiveGoals = async () => {
  try {
    const goals = await getFitnessGoalsByStatus('ACTIVE')
    activeGoals.value = Array.isArray(goals) ? goals : []
    // 在获取目标数据后生成健康提醒
    generateHealthReminders()
  } catch (error) {
    console.error('获取目标失败:', error)
    activeGoals.value = []
    // 即使出错也要生成健康提醒
    generateHealthReminders()
  }
}

// 生成健康提醒
const generateHealthReminders = () => {
  const reminders = []
  
  if (latestHealthData.value) {
    const bmi = latestHealthData.value.bmi
    
    // BMI相关提醒
    if (bmi < 18.5) {
      reminders.push({
        icon: 'Warning',
        iconClass: 'warning-icon',
        message: '您的BMI偏低，请注意增加营养摄入，保持健康饮食。'
      })
    } else if (bmi >= 24 && bmi < 28) {
      reminders.push({
        icon: 'Warning',
        iconClass: 'warning-icon',
        message: '您的BMI偏高，建议适当控制饮食并增加有氧运动。'
      })
    } else if (bmi >= 28) {
      reminders.push({
        icon: 'Warning',
        iconClass: 'warning-icon',
        message: '您的BMI处于肥胖范围，建议咨询医生并制定减重计划。'
      })
    } else {
      reminders.push({
        icon: 'CircleCheck',
        iconClass: 'success-icon',
        message: '您的BMI在正常范围，继续保持健康生活方式！'
      })
    }
    
    // 运动提醒
    if (weeklyExerciseCount.value < 3) {
      reminders.push({
        icon: 'Bell',
        iconClass: 'info-icon',
        message: '本周运动次数不足3次，建议增加运动频率，保持活力。'
      })
    }
    
    // 静息心率提醒
    const restingHeartRate = latestHealthData.value.restingHeartRate
    if (restingHeartRate && restingHeartRate > 80) {
      reminders.push({
        icon: 'Warning',
        iconClass: 'warning-icon',
        message: '您的静息心率偏高，建议增加有氧运动并减少压力。'
      })
    }
  } else {
    reminders.push({
      icon: 'Bell',
      iconClass: 'info-icon',
      message: '尚未记录健康数据，建议添加您的身高体重等基本信息。'
    })
  }
  
  // 只有当确实没有任何目标时，才显示设定目标的提醒
  if (activeGoals.value.length === 0) {
    reminders.push({
      icon: 'Bell',
      iconClass: 'info-icon',
      message: '您还没有设定健身目标，设定目标可以帮助您更好地规划健身计划。'
    })
  }
  
  healthReminders.value = reminders
}

// 格式化时间
const formatDateTime = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 格式化时长
const formatDuration = (minutes) => {
  if (!minutes) return '0分钟'
  if (minutes < 60) return `${minutes}分钟`
  
  const hours = Math.floor(minutes / 60)
  const remainingMinutes = minutes % 60
  
  if (remainingMinutes === 0) return `${hours}小时`
  return `${hours}小时${remainingMinutes}分钟`
}

// 获取BMI对应的样式类
const getBmiClass = (bmi) => {
  if (!bmi) return ''
  if (bmi < 18.5) return 'bmi-low'
  if (bmi >= 24 && bmi < 28) return 'bmi-high'
  if (bmi >= 28) return 'bmi-very-high'
  return 'bmi-normal'
}

// 获取进度条状态
const getProgressStatus = (progress) => {
  if (progress >= 100) return 'success'
  if (progress >= 60) return 'success'
  if (progress >= 20) return ''
  return 'exception'
}

// 获取标签类型
const getTagType = (index) => {
  const types = ['', 'success', 'warning', 'info', 'danger']
  return types[index % types.length]
}

// 导航函数
const goToHealthData = () => router.push('/health-data')
const goToAddHealthData = () => router.push('/health-data/add')
const goToExerciseRecords = () => router.push('/exercise-records')
const goToAddExerciseRecord = () => router.push('/exercise-records/add')
const goToFitnessGoals = () => router.push('/fitness-goals')
const goToAddFitnessGoal = () => router.push('/fitness-goals/add')

onMounted(() => {
  fetchUserInfo()
  fetchLatestHealthData()
  fetchExerciseStats()
  fetchActiveGoals()
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.welcome-card {
  margin-bottom: 20px;
  background: linear-gradient(to right, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.welcome-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-text h2 {
  margin: 0;
  font-weight: 500;
}

.welcome-text p {
  margin: 10px 0 0 0;
  opacity: 0.9;
}

.quick-actions {
  display: flex;
  gap: 10px;
}

.data-card {
  margin-bottom: 20px;
  height: 360px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.data-item {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
}

.label {
  color: #606266;
  font-size: 14px;
}

.value {
  font-weight: bold;
  font-size: 14px;
}

.bmi-low {
  color: #e6a23c;
}

.bmi-normal {
  color: #67c23a;
}

.bmi-high {
  color: #f56c6c;
}

.bmi-very-high {
  color: #f56c6c;
  font-weight: bold;
}

.goal-item {
  margin-bottom: 20px;
}

.goal-title {
  margin-bottom: 8px;
  font-weight: bold;
}

.goal-detail {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  display: flex;
  justify-content: space-between;
}

.more-goals {
  text-align: center;
  color: #909399;
  font-size: 12px;
}

.reminder-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  padding: 10px;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.reminder-item .el-icon {
  margin-right: 10px;
  font-size: 18px;
  flex-shrink: 0;
}

.success-icon {
  color: #67c23a;
}

.warning-icon {
  color: #e6a23c;
}

.info-icon {
  color: #409EFF;
}

.no-data {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.exercise-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.recent-exercises {
  margin-top: 15px;
}

@media (max-width: 768px) {
  .welcome-content {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .quick-actions {
    margin-top: 15px;
  }
}
</style>